package com.dodock.banglapapers.server.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsListBdnews extends DefaultHandler  {

	public static final String TAG_ITEM = "item";
	public static final String TAG_ITEM_TITLE = "title";
	public static final String TAG_ITEM_LINK = "link";
	public static final String TAG_ITEM_DETAILS = "details";
	public static final String TAG_ITEM_IMAGE = "image";
	
	//public static final String TAG_ITEM_IMAGE_URL = "url";
	//public static final String TAG_ITEM_PARENT = "channel";
	//public static final String TAG_ITEM_CATEGORY = "category";
	//public static final String TAG_ITEM_GUID = "guid";
	//public static final String TAG_ITEM_SCROLLNEWS = "scrollNews";
	//public static final String TAG_ITEM_THUMB = "thumb";
	//public static final String TAG_ITEM_PUBDATE = "pubDate";
	//public static final String TAG_ITEM_CAPTION = "caption";
	//public static final String TAG_ITEM_THUMBNAIL = "thumbnail";

	private String BASE_URL_BANGLA = "http://bangla.bdnews24.com/%s?widgetName=rssfeed&widgetId=%s&getXmlFeed=true";
	private String BASE_URL_ENGLISH = "http://bdnews24.com/%s?widgetName=rssfeed&widgetId=%s&getXmlFeed=true"; 

	JsonArray array;
	boolean itemParsing;
	boolean imageParsing;
	String lastTagName;
	JsonObject news;
	private String characters;
	
	/*	Bangla :
		Top : http://bangla.bdnews24.com/?widgetName=rssfeed&widgetId=1151&getXmlFeed=true
		Bangladesh : http://bangla.bdnews24.com/bangladesh/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true
		Politics : http://bangla.bdnews24.com/politics/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true		
		Sports : http://bangla.bdnews24.com/sport/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true
		Cricket : http://bangla.bdnews24.com/cricket/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true
		World : http://bangla.bdnews24.com/world/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true		
		Business : http://bangla.bdnews24.com/business/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true
		Economy : http://bangla.bdnews24.com/economy/?widgetName=rssfeed&widgetId=1211&getXmlFeed=true
		
		English:		
		Top Story : http://bdnews24.com/?widgetName=rssfeed&widgetId=1150&getXmlFeed=true
		Bangladesh : http://bdnews24.com/bangladesh/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		Politics : http://bdnews24.com/politics/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		Sport : http://bdnews24.com/sport/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		Cricket : http://bdnews24.com/cricket/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		World : http://bdnews24.com/world/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		Business : http://bdnews24.com/business/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true		
		Economy : http://bdnews24.com/economy/?widgetName=rssfeed&widgetId=1210&getXmlFeed=true
		
		//URL url = new URL(String.format("http://rss.bdnews24.com/rss/getfeed.php?ln=%s&cid=%s&ct=n", lang, nativeid));
	    // %s = categoryid + "/"
		// %s = 1211 for bangla news, 1151 for bangla top news, 1150 english top news, 1210 for english news
	*/
	
	public String GenerateNewsList(String categoryid, String lang) {
		try{
			URL url = null;
			if(categoryid.equals("top")){
				if(lang.equalsIgnoreCase("en")){
					url = new URL(String.format(BASE_URL_ENGLISH, "", "1150"));
					return generateNewsListFromXmlFeed(url);
				}					
				else{
					url = new URL(String.format(BASE_URL_BANGLA, "", "1151"));
					return generateNewsListFromXmlFeed(url);
				}									
			}
			else{
				if(lang.equalsIgnoreCase("en")){
					url = new URL(String.format(BASE_URL_ENGLISH, categoryid + "/", "1210"));
					return generateNewsListFromXmlFeed(url);
				}					
				else{
					url = new URL(String.format(BASE_URL_BANGLA, categoryid + "/", "1211"));
					return generateNewsListFromXmlFeed(url);
				}	
			}
		}
		catch(Exception ex){
			return "[]";
		}
	}

	
	private String generateNewsListFromXmlFeed(URL url) throws IOException, SAXException, ParserConfigurationException{
		array = new JsonArray();
		itemParsing = false;
		imageParsing = false;
		lastTagName = null;

		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
		StringBuilder xmlString = new StringBuilder();
		String line;
        while ((line = reader.readLine()) != null) {
        	/*line = line.replaceAll("&quot;", "\"");
        	line = line.replaceAll("&apos;", "'");
        	line = line.replaceAll("&amp;", "&");
        	line = line.replaceAll("&lt;", "<");
        	line = line.replaceAll("&gt;", ">");*/
        	
        	/*line = line.replaceAll("&quot;", "\"");
        	line = line.replaceAll("&apos;", "'");
        	line = line.replaceAll("&#38;", "&");
        	line = line.replaceAll("&#60;", "<");
        	line = line.replaceAll("&#62;", ">");
        	
        	line = line.replaceAll("&amp;#39;", "'");
        	line = line.replaceAll("&#39;", "'");
        	line = line.replaceAll("-&-", "-&amp;-");*/
        	xmlString.append(line);
        }
        reader.close();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(new java.io.ByteArrayInputStream(xmlString.toString().getBytes("UTF-8")), this);
		return array.toString();
	}

	public void startElement(String namespaceURI, 
            String localName,
            String qualifiedName,
            Attributes attributes) 
            		throws SAXException {
			lastTagName = qualifiedName;
			if (lastTagName.equalsIgnoreCase(TAG_ITEM)) {
				itemParsing = true;
				news = new JsonObject();
			} else if (lastTagName.equalsIgnoreCase(TAG_ITEM_IMAGE)) {
				imageParsing = true;
			}
	}
	
	public void endElement(String namespaceURI, 
            String simpleName,
            String qualifiedName) 
            throws SAXException {
		
		if (qualifiedName.equalsIgnoreCase(TAG_ITEM)) {
			itemParsing = false;
			array.add(news);
		} else if (qualifiedName.equalsIgnoreCase(TAG_ITEM_IMAGE)) {
			imageParsing = false;
		}
		lastTagName = null;
	}
	
	public void characters(char buf[], int offset, int len) 
            throws SAXException {		
		characters = new String(buf, offset, len);
		if (lastTagName != null) {
			if (lastTagName.equalsIgnoreCase(TAG_ITEM_TITLE)) {
				if (itemParsing && !imageParsing) {
					//characters = characters.replaceAll("&apos;", "");
					//characters = characters.replaceAll("'", "");
					news.addProperty("title", characters);
				}
			} else if (lastTagName.equalsIgnoreCase(TAG_ITEM_DETAILS)) {
				if (itemParsing) {
					characters = characters.replaceAll("&quot;", "\"");
					characters = characters.replaceAll("&apos;", "'");
					characters = characters.replaceAll("&amp;", "&");
					characters = characters.replaceAll("&lt;", "<");
					characters = characters.replaceAll("&gt;", ">");
					String details = characters;
					if(details.contains("<![CDATA[")){
						details = details.replaceAll("<![CDATA[", " ");
						details = details.replaceAll("]]", " ");					
					}					
					news.addProperty("details", details);
				}
			} else if (lastTagName.equalsIgnoreCase(TAG_ITEM_IMAGE)) {
				if (itemParsing && imageParsing) {
					news.addProperty("image", characters);
					JsonArray imgGallery = new JsonArray();
					JsonObject galleryimage = new JsonObject();
					galleryimage.addProperty("url", characters);
					imgGallery.add(galleryimage);
					news.add("gallery", imgGallery);
				}
			} else if (lastTagName.equalsIgnoreCase(TAG_ITEM_LINK)) {
				if (itemParsing && news.has("id") == false){
					news.addProperty("sharelink", characters);					
					news.addProperty("id", characters.substring(characters.lastIndexOf("/")));
				}
			}
		}
    }	
}
